package com.imooc.ecommerce.service;

import com.alibaba.fastjson.JSON;
import com.imooc.ecommerce.dao.EcommerceLogisticsDao;
import com.imooc.ecommerce.entity.EcommerceLogistics;
import com.imooc.ecommerce.order.LogisticsMessage;
import com.imooc.ecommerce.sink.LogisticsSink;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;

/**
 * <p>物流服务实现
 *
 * @author Yaxi.Zhang
 * @since 2022/11/17 20:22
 */
@Slf4j
@EnableBinding(LogisticsSink.class)
public class LogisticsServiceImpl {

    private final EcommerceLogisticsDao logisticsDao;

    public LogisticsServiceImpl(EcommerceLogisticsDao logisticsDao) {
        this.logisticsDao = logisticsDao;
    }

    /**
     * <p>订阅监听订单微服务发送的物流消息
     */
    @StreamListener("logisticsInput")
    public void consumeLogisticsMessage(@Payload Object payload) {
        log.info("receive and consume logistics message: [{}]", payload.toString());
        LogisticsMessage logisticsMessage = JSON.parseObject(payload.toString(), LogisticsMessage.class);
        EcommerceLogistics ecommerceLogistics = logisticsDao.save(
                new EcommerceLogistics(logisticsMessage.getUserId(), logisticsMessage.getOrderId(), logisticsMessage.getAddressId(), logisticsMessage.getExtraInfo()));
        log.info("consume logistics message success: [{}]", ecommerceLogistics.getId());
    }

}
